<%@ page import="org.jawa.core.database.DbConnectionManager" pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>

<%
    // Get parameters
    boolean execute = request.getParameter("execute") != null;
    String sql = request.getParameter("sql");
%>

<html>
    <head>
        <title>DB Access Tool</title>
        <meta name="pageID" content="db-access"/>
    </head>
    <body>

<div class="information">
   数据库工具.
</div>

<div>
    <h3>SQL 语名:</h3>
    <form action="db-access.jsp" method="post">
        <textarea rows="10" cols="80" name="sql"><%= sql != null ? sql : "" %></textarea>
        <br />
        <input type="submit" name="execute" value="Execute SQL"/>
    </form>
</div>

<div>
    <h3>SQL 结果:</h3>
    <div style="width: 100%; height: 300px; border: 1.0px solid #000000; overflow: scroll" id="output">
<%
    // Handle an execution
    if (execute) {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            con = DbConnectionManager.getConnection();
            stmt = con.createStatement();
            // SQL
            stmt.execute(sql);
            rs = stmt.getResultSet();
            if (rs == null) {
                out.println("<p>结果: updateCount = <b>" + stmt.getUpdateCount() + "</p>");
            } else {
                out.println("<br>结果:");

                ResultSetMetaData md = rs.getMetaData();
                int count = md.getColumnCount();
                out.println("<table border=1>");
                out.print("<tr>");
                for (int i=1; i<=count; i++) {
                    out.print("<th>");
                    out.print(md.getColumnName(i));
                }
                out.println("</tr>");
                while (rs.next()) {
                    out.print("<tr>");
                    for (int i=1; i<=count; i++) {
                        out.print("<td>");
                        out.print(rs.getString(i));
                    }
                    out.println("</tr>");
                }
            }
            out.println("</table>");
        } catch (SQLException ex) {
            out.print("<B>" + getClass() + ": SQL Error:</B>\n" + ex);
        }
        finally {
            DbConnectionManager.closeConnection(rs, stmt, con);
        }
    }
%>
    </div>
</div>

</body>
</html>